package com.gec.controller;

import com.alibaba.fastjson.JSONObject;
import com.gec.domain.Option;
import com.gec.domain.PageBean;
import com.gec.domain.User;
import com.gec.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author Aniki
 * @date 2021-12-14
 */
@Controller
@RequestMapping("/User")
public class UserController extends  BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping("/addUser")
    public  String addUser(){

        return "user/addUser";
    }

    @RequestMapping(value = "/jsonDeptOptions",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String jsonDeptOptions(){
        List<Option> list = userService.getDeptOptions();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deptJson",list);
        return jsonObject.toString();
    }

    @RequestMapping(value = "/jsonRoleOptions",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String jsonRoleOptions(){
        List<Option> list = userService.getRoleOptions();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("roleJson",list);
        return jsonObject.toString();
    }

    @RequestMapping("/viewList")
    public String viewList(){
        return "user/list";
    }

    @RequestMapping("/index")
    public String index(){
        return "/index";
    }

    @RequestMapping("/showIndex")
    public String showIndex(){
        return "/showIndex";
    }

    @RequestMapping(value = "/jsonList",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String jsonList(@RequestParam Map<String,String> data){
         /**获取PageData页信息*/
        PageData pageData = new PageData(data);
        //调用userService获取用户列表
         PageBean pBean = null;
        try {
            pBean = userService.getUserList(
                    pageData.getPage(),
                    pageData.getLimit(),
                    pageData.getKeywords()
                  );
            String json = packJSON(pBean);
                    return  json;
        } catch (Exception e) {
            e.printStackTrace();
            return setErrorMsg(e);
        }
    }

    @RequestMapping(value = "/delete",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String delUser(String id) {
         String respTxt = "";
        JSONObject jsonObject = new JSONObject();
        try {
                 userService.delUser(id);
            jsonObject.put("result","success");
            respTxt = jsonObject.toString();
        } catch (Exception e) {
            e.printStackTrace();
            respTxt = setErrorMsg(e);
        }
        return respTxt;
    }


    @RequestMapping(value = "/saveUser",produces  = "text/html;charset=UTF-8" )
    @ResponseBody
    public  String saveUser(User user, @RequestParam("role")String role) {
        String respTxt = "";
        JSONObject jsonObject = new JSONObject();
        String userId = user.getId();
        String password = user.getPassword();
        Md5Hash passwordMd5 = new Md5Hash(password);
        user.setPassword(String.valueOf(passwordMd5));
        try {
            userService.saveUser(user);
            userService.saveRoleId(userId,role);
            jsonObject.put("result","success");
            respTxt = jsonObject.toString();
        } catch (Exception e) {
            e.printStackTrace();
            respTxt = setErrorMsg(e);
        }
        return respTxt;
    }

    @RequestMapping(value = "/update",produces  = "text/html;charset=UTF-8" )
    @ResponseBody
    public  String updateUser(User user) {
        String respTxt = "";
        JSONObject jsonObject = new JSONObject();
        try {
            userService.updateUser(user);
            jsonObject.put("result","success");
            respTxt = jsonObject.toString();
        } catch (Exception e) {
            e.printStackTrace();
            respTxt = setErrorMsg(e);
        }
        return respTxt;
    }


    @RequestMapping(value = "/getUser",produces  = "text/html;charset=UTF-8" )
    @ResponseBody
    public  String getUser(@RequestParam("id") String id) {
        String respTxt = "";
        JSONObject jsonObject = new JSONObject();
        try {
            User user = userService.getUser(id);
            jsonObject.put("result","success");
            jsonObject.put("user",user);
            respTxt = jsonObject.toString();
        } catch (Exception e) {
            e.printStackTrace();
            respTxt = setErrorMsg(e);
        }
        return respTxt;
    }


        /**登录方法*/
    @RequestMapping("/login")
    public String login(@RequestParam("username")String username, @RequestParam("password")String password){
        //{1}创建令牌, 载入 用户名+密码
        UsernamePasswordToken token = new UsernamePasswordToken(username, password );
        //{2}获取主体对象
        Subject subject = SecurityUtils.getSubject();
        String errcode = "0";
        try{
            //{3}执行登录
            subject.login( token );
            //{4}尝试使用 shiro 提供的 session
            Session session = subject.getSession(true);
            //{5}通过主体获取 [数据库] 中的用户身份信息。
            Object user = subject.getPrincipal();
            //{6}设置到会话域。
            session.setAttribute("user", user);
            //{7}重定向到 主页(成功)
            return "redirect:/User/index";
        }catch(UnknownAccountException e){
            errcode = "1";
        }catch(IncorrectCredentialsException e){
            errcode = "2";
        }
        return "redirect:/User/showLogin?errcode="+ errcode;
    }

    @RequestMapping("/showLogin")
    public String showLogin(){
        return "/login";
    }

    @RequestMapping("/loginOut")
    public String loginOut(){

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
      /**Session session = subject.getSession();
        System.out.println("==================================================================");
        User getseesion = (User) session.getAttribute("user");
        System.out.println(getseesion);
        System.out.println("==================================================================");
*/
        return "redirect:/User/showLogin";
    }
}
